/**
 * Copyright 2016-2018 mobaas.com
 */
package com.mobaas.devops.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.mobaas.devops.Constants;
import com.mobaas.devops.JsonResult;
import com.mobaas.devops.model.Admin;
import com.mobaas.devops.service.AdminService;
import com.mobaas.devops.util.CryptoUtils;
import com.mobaas.devops.util.RequestUtils;

/**
 * 
 * @author billy zhang
 * 
 */
@Controller
public class HomeController extends BaseController {
	
	@Autowired
	private AdminService adminService;

	@RequestMapping(value = "/", method=RequestMethod.GET)
    public String home(){
        return "forward:/index";
    }

    @RequestMapping(value = "/index")
    public ModelAndView index(){

        return new ModelAndView("/index");
    }

    @RequestMapping(value = "/denied")
    public ModelAndView denied(){

        return new ModelAndView("/denied");
    }

    @GetMapping(value = "/login")
    public ModelAndView login(){

        return new ModelAndView("/login");
    }


    @PostMapping(value = "/login")
    @ResponseBody
    public Map<String, Object> loginPost(
    			@RequestParam("username")String username, 
    			@RequestParam("password")String password) throws Exception {
       
        Map<String,Object> map=new HashMap<>();
    	  String loginIp = RequestUtils.getRealIP(getRequest());

    	  JsonResult<Admin> result=adminService.selectAdminForLogin(username, password, loginIp);
	    	
    	  if(result.getErrCode()==0) {
	
	    		Admin admin = result.getData();
	
	
	    		if (admin.getState() == 0) {
		    		// 设置Cookie
		    		Cookie cookie = new Cookie(Constants.ADMIN_COOKIEID, CryptoUtils.encryptDES(Constants.ADMIN_KEY, admin.getId() + ""));
		    		getResponse().addCookie(cookie);
		    		
                map.put("code",0);
                map.put("msg","登录成功");
                return map;
	    		} else {
                map.put("code",-1);
                map.put("msg","此管理员已禁用");
	    			return map;
	    		}
	    	}else {
            map.put("code",result.getErrCode());
            map.put("msg",result.getErrMsg());
            return map;
	    	}
    }
    
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView logout() {

	    getRequest().getSession().invalidate();
	
	    	 Cookie[] cookies = getRequest().getCookies();
         if(null!=cookies){
             for(Cookie cookie : cookies){
                 if(Constants.ADMIN_COOKIEID.equals(cookie.getName())){
                	 cookie.setValue(null);
                 	cookie.setMaxAge(-1);
                 	cookie.setPath("/");
                 	getResponse().addCookie(cookie);
                 	break;
                 }
             }
         }

	    	ModelAndView model=new ModelAndView();
	    	model.setViewName("redirect:/login");
	    	return model;

    }

	@GetMapping(value="changePwd")
    public ModelAndView changePwd() {
    	ModelAndView model=new ModelAndView();

        model.setViewName("changepwd");

        return model;
    }

	@PostMapping(value="changePwd")
	@ResponseBody
    public String changePwdPost(
    		@RequestParam("passwd")String passwd,
    		@RequestParam("passwd2")String newPasswd,
    		HttpServletRequest request) {

	    	Admin adm = getAdmin();
	    	String encPasswd = CryptoUtils.MD5(CryptoUtils.MD5(passwd) + adm.getPwdSalt());
	    	
	    	if (adm.getPassword().equalsIgnoreCase(encPasswd)) {
	    		String newEncPasswd = CryptoUtils.MD5(CryptoUtils.MD5(newPasswd) + adm.getPwdSalt());
	    		adm.setPassword(newEncPasswd);
	    		adminService.updateAdmin(adm);
	
	            return "{\"errCode\":0}";
	    	} else {
	            return "{\"errCode\":-1}";
	    	}
    }

}
